<template>
  <div class="common-form">
    <div class="top-nav">
      <p class="nav-title">专栏管理 > 专栏定价信息</p>
    </div>
    <common-form :formConfig="formConfig" @input="onFormUpdated"></common-form>
    <div class="form-operation">
      <button class="form-btn btn-primary" :class="{'btn-disable':publishing}"  @click="doSubmit(1)">发布</button>
      <button class="form-btn" :class="{'btn-disable':publishing}"  @click="doSubmit(0)">保存</button>
      <button class="form-btn" :class="{'btn-disable':publishing}"  @click="doCancel">取消</button>
    </div>
    <div class="form-tips">
      <p v-if="isJournal">专栏开始时间、持续时间、订阅价格发布后不可更改，请谨慎操作</p>
      <p v-if="isJournal">期刊专栏至少要填写一个售卖周期才能发布</p>
      <p v-if="!isJournal">定价后，不可修改，请谨慎操作</p>
    </div>
  </div>
</template>

<script>
import CommonForm from '../../form/CommonForm.vue';
import * as types from '../../../store/mutation-types';
import Tools from 'utils/tools.js';

export default {
  name: 'createPrice',
  components:{
    "common-form":CommonForm
  },
  data() {
    let editingPriceData = this.$store.state.createInfo.editingPriceData;
    return {
      formData: {},
      validate: {},
      formConfig: this.$route.params.id == 1 ? [{//是否为期刊
        name: 'startTime',
        title: '本期开始时间',
        desc: '',
        require: true,
        type: 'datepicker',
        value: editingPriceData.startTime && Tools.dateFormat(editingPriceData.startTime, 'yyyy-MM-dd')
      }, {
        name: 'endTime',
        title: '本期结束时间',
        desc: '专栏开始时间、持续时间请与合同保持一致',
        require: true,
        type: 'datepicker',
        value: editingPriceData.endTime && Tools.dateFormat(editingPriceData.endTime, 'yyyy-MM-dd')
      }, {
        name: 'duration',
        title: '本期持续时间',
        desc: '专栏大致的持续时间，以月、年为单位',
        require: true,
        type: 'selecttext',
        value: editingPriceData.duration || "1-年",
        extra: {
          option: [{
            key: '年',
            value: '年',
            disabled: false
          }, {
            key: '月',
            value: '月',
            disabled: false
          }]
        }
      }, {
        name: 'price',
        title: '本期市场价格',
        desc: '',
        require: true,
        type: 'radio',
        value: editingPriceData.price || 199,
        extra: {
          radio:[{
            key: 1.73,
            text: '1.73元',
            checked: true
          },{
            key: 173,
            text: '173元',
            checked: true
          },{
            key: 1,
            text: '1元',
            checked: true
          },{
            key: 99,
            text: '99元',
            checked: true
          },{
            key: 199,
            text: '199元',
            checked: true
          }]
        },
      }]:[{
        name: 'price',
        title: '市场价格',
        desc: '',
        require: true,
        type: 'radio',
        value: editingPriceData.price || 199,
        extra: {
          radio:[{
            key: 1.73,
            text: '1.73元',
            checked: true
          },{
            key: 173,
            text: '173元',
            checked: true
          },{
            key: 1,
            text: '1元',
            checked: true
          },{
            key: 99,
            text: '99元',
            checked: true
          },{
            key: 199,
            text: '199元',
            checked: true
          }]
        },
      }],
      publishing: false,
      submit: false
    };
  },
  computed: {
    hasChange: {
      cache: false,
      get() {
        let changed = 0;
        this.formConfig.forEach((item) => {
          let formItem = this.formData[item.name];
          if (formItem && formItem !== item.value) {
            changed++;
          }
        });
        return changed;
      }
    },
    isJournal() {
      return this.$route.params.id == 1;
    },
    editingPriceData() {
      return this.$store.state.createInfo.editingPriceData;
    }
  },
  methods: {
    onFormUpdated({formData, validate, byUser}) {
      this.formData = formData;
      this.validate = validate;
    },
    doSubmit(flagType) {//0|保存，1|发布
      if (!this.publishing) {
        for (let i = 0; i < this.formConfig.length; i++) {
          let config = this.formConfig[i];
          let validate = this.validate[config.name];
          if (!validate.ok) {
            this.$store.dispatch('alert', `${config.title}${validate.info}`);
            return false;
          }
        }

        if(this.$store.state.createInfo.specialColumnId && !this.editingPriceData.specialColumnId){//获取到了info，没获取到price
          this.formData.specialColumnId = this.$store.state.createInfo.specialColumnId;
          this.formData.flag = flagType;
          this.publishing = true;

          this.formData.id = this.editingPriceData.id;
          this.$store.dispatch('updateFormDataPrice', this.formData);//更新FormData
          this.$store.dispatch('submitPrice').then(() => {//第二步提交
            this.clearValue();
            this.submit = true;
            this.publishing = false;
          }, () => {
            this.publishing = false;
          });
        }else{//创建和修改
          if(this.editingPriceData.specialColumnId){//修改-读取id
            this.$store.dispatch('updateFormDataInfo', {id:this.editingPriceData.specialColumnId});//更新FormData
          }

          this.$store.dispatch('submitForm').then((specialColumnId) => {//第一步提交
            this.formData.specialColumnId = specialColumnId;//第一步提交成功返回specialColumnId
            this.formData.flag = flagType;
            this.publishing = true;

            this.formData.id = this.editingPriceData.id;
            this.$store.dispatch('updateFormDataPrice', this.formData);//更新FormData
            this.$store.dispatch('submitPrice').then(() => {//第二步提交
              this.clearValue();
              this.submit = true;
              this.publishing = false;
            }, () => {
              this.publishing = false;
            });
          }, (msg) => {
            this.$store.dispatch('alert', msg);
            this.publishing = false;
          });
        }
      }
    },
    doCancel() {
      this.$router.push('/columns');
    },
    clearValue() {
      this.formConfig.forEach((input) => input.value = null)
    }
  },
  beforeRouteEnter(to, from, next){
    next(vm => {
      if (vm.$store.state.user.status !== 1) {
        vm.$router.push('/columns')
      }
    })
  },
  beforeRouteLeave(to, from, next) {
    if (!this.submit && this.hasChange > 0){
      this.$store.dispatch('confirm', '您已输入的内容将会丢失，是否确定？').then(()=> {
        this.$store.commit(types.CLEAR_EDIT_STATE);
        next();
      }, ()=> {
        next(false);
      })
    }else{
      this.$store.commit(types.CLEAR_EDIT_STATE);
      next();
    }
  }
};
</script>

<style lang="less" rel="stylesheet/less">
.common-form{
  .top-nav{
    height: 40px;
    margin-bottom: 30px;
    border-bottom: 1px solid #2e9057;
    .nav-title{
      font-size: 20px;
      color: #2e9057;
    }
  }
}
.form-tips{
  width: 520px;
  margin: 15px auto;
  p{
    line-height: 150%;
    color: #999;
  }
}
</style>
